import requests
import os
import json
import re

# 接口的基础URL
LOGIN_URL = "https://qv20czm4gd.execute-api.us-west-1.amazonaws.com/dev/v1/login2"
CREATE_OTA_JOB_URL = "https://qv20czm4gd.execute-api.us-west-1.amazonaws.com/dev/v1/admin/otajob?user_approval=true&notify=false"

# 登录的账号密码
login_data = {
    "user_name": "developer@makeblock.com",
    "password": "1234qweR"
}

# 缓存文件名
CACHE_FILE_NAME = "cache_data.json"

def load_cache_data():
    """
    从本地缓存文件中加载数据，如果文件不存在则返回空字典
    """
    if os.path.exists(CACHE_FILE_NAME):
        with open(CACHE_FILE_NAME, 'r') as file:
            return json.load(file)
    return {}


def save_cache_data(cache_data):
    """
    将数据保存到本地缓存文件（以JSON格式）
    """
    with open(CACHE_FILE_NAME, 'w') as file:
        json.dump(cache_data, file)


def login():
    """
    通过POST请求登录接口获取授权（提取accesstoken作为授权信息）
    """
    response = requests.post(LOGIN_URL, json=login_data)
    if response.status_code == 200:
        authorization = response.json().get('accesstoken')
        cache_data = load_cache_data()
        cache_data['authorization'] = authorization
        save_cache_data(cache_data)
        return authorization
    else:
        raise Exception(f"登录失败，状态码: {response.status_code}")


def increment_job_name(job_name):
    """
    根据规则递增ota_job_name
    """
    match = re.match(r'(.*)_(\d+)$', job_name)
    if match:
        base_name = match.group(1)
        num = int(match.group(2))
        new_num = num + 1
        return f"{base_name}_{new_num}"
    else:
        return f"{job_name}_1"


def create_ota_job(metadata, description):
    """
    通过POST请求创建ota job，相关参数从cache_data中获取
    """
    cache_data = load_cache_data()
    authorization = cache_data.get('authorization')
    ota_image_id = cache_data.get('ota_image_id')
    ota_job_name = cache_data.get('ota_job_name')
    nodes = cache_data.get('nodes')

    if authorization is None or ota_image_id is None or ota_job_name is None or nodes is None:
        raise ValueError("缓存数据不完整，缺少必要的创建ota job参数")

    # 递增ota_job_name
    new_ota_job_name = increment_job_name(ota_job_name)

    headers = {
        "Authorization": authorization
    }
    data = {
        "ota_image_id": ota_image_id,
        "ota_job_name": new_ota_job_name,
        "nodes": nodes,
        "metadata": metadata,
        "description": description
    }
    response = requests.post(CREATE_OTA_JOB_URL, headers=headers, json=data)
    if response.status_code == 200:
        print("OTA Job创建成功")
        # 更新缓存中的ota_job_name
        cache_data['ota_job_name'] = new_ota_job_name
        save_cache_data(cache_data)
        return response.json()
    else:
        print(f"首次创建OTA Job失败，状态码: {response.status_code}，尝试重新登录后再次创建")
        authorization = login()
        cache_data = load_cache_data()
        cache_data['authorization'] = authorization
        cache_data['ota_image_id'] = ota_image_id
        cache_data['ota_job_name'] = new_ota_job_name
        cache_data['nodes'] = nodes
        save_cache_data(cache_data)

        headers = {
            "Authorization": authorization
        }
        new_response = requests.post(CREATE_OTA_JOB_URL, headers=headers, json=data)
        if new_response.status_code == 200:
            print("再次尝试后OTA Job创建成功")
            # 更新缓存中的ota_job_name
            cache_data['ota_job_name'] = new_ota_job_name
            save_cache_data(cache_data)
            return new_response.json()
        else:
            raise Exception(f"再次创建OTA Job失败，状态码: {new_response.status_code}")


if __name__ == "__main__":
    # 参数
    metadata = {"esp.ota.target":"host_mcu"}
    description = "mcu ota test"

    create_ota_job(metadata, description)
